package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotDelException;
import com.rfid.project.model.AftersaleRecord;
import com.rfid.project.service.AftersaleRecordService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.model.Project;
import com.rfid.project.service.ProjectService;
import com.rfid.project.model.Product;
import com.rfid.project.service.ProductService;
import com.rfid.project.model.Customer;
import com.rfid.project.service.CustomerService;
import com.rfid.project.model.AftersaleHandleType;
import com.rfid.project.service.AftersaleHandleTypeService;
import com.rfid.project.util.StringUtil;

@Controller
public class AftersaleRecordController {

	private static final Logger logger = LoggerFactory.getLogger(AftersaleRecordController.class);

	@Autowired
	private AftersaleRecordService aftersaleRecordService;

	@Autowired
	private PeopleService peopleService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private ProductService productService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private AftersaleHandleTypeService aftersaleHandleTypeService;

	@RequestMapping(value = "/afterSaleAnalyse")
	public String afterSaleAnalyse(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "afterSaleAnalyse";
	}

	@RequestMapping(value = "/aftersaleRecordmgr")
	public String aftersaleRecordmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Project> projects = projectService.findAll();
		model.addAttribute("projects", projects);

		List<Product> products = productService.findAll();
		model.addAttribute("products", products);

		List<Customer> customers = customerService.findAll();
		model.addAttribute("customers", customers);

		List<AftersaleHandleType> aftersaleHandleTypes = aftersaleHandleTypeService.findAll();
		model.addAttribute("aftersaleHandleTypes", aftersaleHandleTypes);

		List<People> checkPersons = peopleService.findAll();
		model.addAttribute("persons", checkPersons);
		return "aftersaleRecordmgr";
	}
	
	
	@RequestMapping(value = "/aftersaleQuery")
	public String aftersaleQuery(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Project> projects = projectService.findAll();
		model.addAttribute("projects", projects);

		List<Product> products = productService.findAll();
		model.addAttribute("products", products);

		List<Customer> customers = customerService.findAll();
		model.addAttribute("customers", customers);

		List<AftersaleHandleType> aftersaleHandleTypes = aftersaleHandleTypeService
				.findAll();
		model.addAttribute("aftersaleHandleTypes", aftersaleHandleTypes);

		List<People> checkPersons = peopleService.findAll();
		model.addAttribute("persons", checkPersons);
		return "aftersaleQuery";
	}

	@RequestMapping(value = "/queryAftersaleRecord")
	public String queryAftersaleRecord(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "registerPersonId", defaultValue = "-1") Long registerPersonId,
			@RequestParam(value = "issueDescription", defaultValue = "") String issueDescription,
			@RequestParam(value = "outOfWarrantySign", defaultValue = "") String outOfWarrantySign,
			@RequestParam(value = "registerTimeBegin", defaultValue = "") Date registerTimeBegin,
			@RequestParam(value = "registerTimeEnd", defaultValue = "") Date registerTimeEnd,
			@RequestParam(value = "expectFinishDateBegin", defaultValue = "") Date expectFinishDateBegin,
			@RequestParam(value = "expectFinishDateEnd", defaultValue = "") Date expectFinishDateEnd,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "productId", defaultValue = "-1") Long productId,
			@RequestParam(value = "customerId", defaultValue = "-1") Long customerId,
			@RequestParam(value = "customerName", defaultValue = "") String customerName,
			@RequestParam(value = "contactPerson", defaultValue = "") String contactPerson,
			@RequestParam(value = "contactPersonTel", defaultValue = "") String contactPersonTel,
			@RequestParam(value = "handlePersonId", defaultValue = "-1") Long handlePersonId,
			@RequestParam(value = "aftersaleHandleTypeId", defaultValue = "-1") Long aftersaleHandleTypeId,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "actualFinishTimeBegin", defaultValue = "") Date actualFinishTimeBegin,
			@RequestParam(value = "actualFinishTimeEnd", defaultValue = "") Date actualFinishTimeEnd,
			@RequestParam(value = "productSequenceNo", defaultValue = "") String productSequenceNo,
			@RequestParam(value = "checkPersonId", defaultValue = "-1") Long checkPersonId,
			@RequestParam(value = "checkTimeBegin", defaultValue = "") Date checkTimeBegin,
			@RequestParam(value = "checkTimeEnd", defaultValue = "") Date checkTimeEnd,
			@RequestParam(value = "returnDateBegin", defaultValue = "") Date returnDateBegin,
			@RequestParam(value = "returnDateEnd", defaultValue = "") Date returnDateEnd,
			@RequestParam(value = "finishDateBegin", defaultValue = "") Date finishDateBegin,
			@RequestParam(value = "finishDateEnd", defaultValue = "") Date finishDateEnd,
			@RequestParam(value = "deliveryDateBegin", defaultValue = "") Date deliveryDateBegin,
			@RequestParam(value = "deliveryDateEnd", defaultValue = "") Date deliveryDateEnd,
			@RequestParam(value = "issueReason", defaultValue = "") String issueReason,
			@RequestParam(value = "handleDescription", defaultValue = "") String handleDescription,
			@RequestParam(value = "handleCostDescription", defaultValue = "") String handleCostDescription,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<AftersaleRecord> aftersaleRecords = aftersaleRecordService
				.findAll(registerPersonId, issueDescription, outOfWarrantySign,
						registerTimeBegin, registerTimeEnd,
						expectFinishDateBegin, expectFinishDateEnd, projectId,
						productId, customerId, customerName, contactPerson,
						contactPersonTel, handlePersonId,
						aftersaleHandleTypeId, status, actualFinishTimeBegin,
						actualFinishTimeEnd, productSequenceNo, checkPersonId,
						checkTimeBegin, checkTimeEnd, returnDateBegin,
						returnDateEnd, finishDateBegin, finishDateEnd,
						deliveryDateBegin, deliveryDateEnd, issueReason,
						handleDescription, handleCostDescription, remark,
						pageNumber, pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", aftersaleRecords.getTotalElements());
		JSONArray models = new JSONArray();
		for (AftersaleRecord item : aftersaleRecords) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findAftersaleRecord")
	public String findAftersaleRecord(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		AftersaleRecord aftersaleRecord = aftersaleRecordService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(aftersaleRecord, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}


	private void wrapData(AftersaleRecord item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("status", item.getStatus());
		mod.put("contactPersonTel", item.getContactPersonTel());
		mod.put("contactPerson", item.getContactPerson());
		mod.put("customerName", item.getCustomerName());
		mod.put("expectFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getExpectFinishDate()));
		mod.put("registerTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getRegisterTime()));
		mod.put("outOfWarrantySign", item.getOutOfWarrantySign());
		mod.put("issueDescription", item.getIssueDescription());
		
		mod.put("registerPersonId", item.getRegisterPerson().getId());
		mod.put("registerPersonName", item.getRegisterPerson().getName());
		mod.put("projectId", item.getProject().getId());
		mod.put("projectName", item.getProject().getName());
		mod.put("productId", item.getProduct().getId());
		mod.put("productName", item.getProduct().getName());
		mod.put("cusId", item.getCustomer().getId());
		mod.put("cusName", item.getCustomer().getName());
		mod.put("handlePersonId", item.getHandlePerson().getId());
		mod.put("handlePersonName", item.getHandlePerson().getName());
		mod.put("aftersaleHandleTypeId", item.getAftersaleHandleType().getId());
		mod.put("aftersaleHandleTypeName", item.getAftersaleHandleType().getName());
		mod.put("actualFinishTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getActualFinishTime()));
		mod.put("consumeWorktime", item.getConsumeWorktime());
		mod.put("productSequenceNo", item.getProductSequenceNo());
		mod.put("checkPersonId", item.getCheckPerson().getId());
		mod.put("checkPersonName", item.getCheckPerson().getName());
		mod.put("checkTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getCheckTime()));
		mod.put("returnDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getReturnDate()));
		mod.put("finishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getFinishDate()));
		mod.put("deliveryDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getDeliveryDate()));
		mod.put("issueReason", item.getIssueReason());
		mod.put("handleFee", item.getHandleFee());
		mod.put("handleDescription", item.getHandleDescription());
		mod.put("handleCost", item.getHandleCost());
		mod.put("handleCostDescription", item.getHandleCostDescription());
		mod.put("remark", StringUtil.getString(item.getRemark()));
	}

	@RequestMapping(value = "/editAftersaleRecord", method = RequestMethod.POST)
	public String editAftersaleRecord(HttpServletRequest request,
			HttpServletResponse response, @Valid AftersaleRecord aftersaleRecord,
			Model model, RedirectAttributes redirectAttributes) {
		aftersaleRecordService.saveAftersaleRecord(aftersaleRecord);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delAftersaleRecord")
	public String delAftersaleRecord(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.aftersaleRecordService.deleteAftersaleRecord(id);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg",e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {

		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
